<?php
class User extends CI_Controller{


	public function login(){
		$content['error'] = 0;
		$this->form_validation->set_rules('user', 'Username', 'required');
		$this->form_validation->set_rules('pass', 'Password', 'required');

		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			if($this->form_validation->run() != FALSE){
				$user = $this->input->post('user');
				$pass = $this->input->post('pass');

				$data = $this->User_model->select($user,$pass);
				if($data != null){
					$this->session->set_userdata('user',$data->ID);
					if($this->session->userdata('prevURL') != NULL){
						$prevURL = $this->session->userdata('prevURL');
						$this->session->unset_userdata('prevURL');
						redirect($prevURL);
					}else{
						redirect('');

						exit;
					}
				}else{
					$content['error'] = 1;
					$this->load->view('user/login',$content);
				}

			}else{
				$this->load->view('user/login',$content);
			}

		}else{

			$this->load->view('user/login',$content);
		}
	}

	public function register(){

		$this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.user_login]');
		$this->form_validation->set_rules('password', 'Password', 'required');
		$this->form_validation->set_rules('email', 'Email', 'required|is_unique[users.user_email]|matches[cfemail]');
		$this->form_validation->set_rules('cfemail', 'Confirm Email', 'required');
		$this->form_validation->set_rules('fullname', 'Full Name', 'required');
		$this->form_validation->set_rules('address', 'Address', 'required');
		$this->form_validation->set_rules('phone', 'Phone', 'required');

		if($_SERVER['REQUEST_METHOD'] == 'POST'){
			if ($this->form_validation->run() != FALSE)
			{
				$username = $this->input->post('username');
				$password = $this->input->post('password');
				$email = $this->input->post('email');
				$fullname = $this->input->post('fullname');
				$address = $this->input->post('address');
				$phone = $this->input->post('phone');
				$result = $this->User_model->insert($username,$password,$fullname,$email,$address,$phone);
				if($result){
					$data = $this->User_model->select($username,$password);
					$this->session->set_userdata('user',$data->ID);
					redirect('');
					exit();
				}else{
					echo 'failed';
					//$this->load->view('user/register');
				}
			}
			else
			{
				$this->load->view('user/register');
			}
		}else{
			$this->load->view('user/register');
		}
			
	}

	public function detail($id){
		
		if($this->session->userdata('user') == NULL){
			$this->session->set_userdata('prevURL',"user/detail/$id");
			redirect('/user/login');
			exit();
		}
		$this->load->view('user/detail');
		
	}
}